﻿using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 删除销售订单处理器
    /// </summary>
    public class DeleteSalesOrderHandler : IRequestHandler<DeleteSalesOrderCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<SalesOrder> salesOrderRepository;
        private readonly IBaseRepository<SalesOrderDetail> salesOrderDetailRepository;
        private readonly ILogger<DeleteSalesOrderHandler> logger;

        public DeleteSalesOrderHandler(
            IBaseRepository<SalesOrder> salesOrderRepository,
            IBaseRepository<SalesOrderDetail> salesOrderDetailRepository,
            ILogger<DeleteSalesOrderHandler> logger)
        {
            this.salesOrderRepository = salesOrderRepository;
            this.salesOrderDetailRepository = salesOrderDetailRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理删除销售订单请求
        /// </summary>
        /// <param name="request">删除请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public Task<APIResult<bool>> Handle(DeleteSalesOrderCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            try
            {
                logger.LogInformation("开始删除销售订单，订单ID：{OrderId}", request.Id);

                // 1. 检查销售订单是否存在
                var salesOrder = salesOrderRepository.GetModel(request.Id);
                if (salesOrder == null)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "销售订单不存在或已被删除";
                    logger.LogWarning("销售订单不存在或已被删除，ID：{OrderId}", request.Id);
                    return Task.FromResult(result);
                }
                if(salesOrder.OrderStatus !="开立")
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "开立的销售订单才可以删除";
                    logger.LogWarning("开立的销售订单才可以删除，ID：{OrderId}", request.Id);
                    return Task.FromResult(result);
                }

                logger.LogInformation("找到销售订单：{OrderCode} (ID：{OrderId})", salesOrder.OrderCode, salesOrder.Id);

                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        // 2. 逻辑删除销售订单明细
                        var orderDetails = salesOrderDetailRepository.GetAll("SalesOrderId = @SalesOrderId AND IsDeleted = false", 
                            new { SalesOrderId = request.Id });
                        
                        if (orderDetails.Any())
                        {
                            logger.LogInformation("开始删除销售订单明细，数量：{DetailCount}", orderDetails.Count);
                            
                            foreach (var detail in orderDetails)
                            {
                                detail.IsDeleted = true;
                                var updateResult = salesOrderDetailRepository.Update(detail);
                                if (updateResult <= 0)
                                {
                                    throw new InvalidOperationException($"销售订单明细删除失败，ID：{detail.Id}");
                                }
                            }
                            
                            logger.LogInformation("销售订单明细删除成功，数量：{DetailCount}", orderDetails.Count);
                        }

                        // 3. 逻辑删除销售订单
                        salesOrder.IsDeleted = true;
                        var result1 = salesOrderRepository.Update(salesOrder);
                        if (result1 <= 0)
                        {
                            throw new InvalidOperationException($"销售订单删除失败，ID：{salesOrder.Id}");
                        }
                        
                        logger.LogInformation("销售订单删除成功，ID：{OrderId}", salesOrder.Id);

                        // 4. 提交事务
                        transaction.Complete();

                        result.Code = APIEnums.Success;
                        result.Data = true;
                        result.Msg = "销售订单删除成功";
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "删除销售订单过程中发生错误：{Message}", ex.Message);
                        result.Code = APIEnums.Error;
                        result.Msg = "删除销售订单失败";
                        result.Data = false;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除销售订单失败：{Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "删除销售订单失败";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
}
